<template>
  <div>
    <div
      v-if="rowConditions && rowConditions.length > 0"
      style="display: flex"
    >
      <div class="name_class">
        <svg
          t="1711765253572"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="4381"
          id="mx_n_1711765253573"
          width="20"
          height="20"
        >
          <!-- 加粗 -->
          <path
            d="M806.912 282.5216H217.088c-18.1248 0-32.8704 14.7456-32.8704 32.8704 0 18.1248 14.7456 32.8704 32.8704 32.8704h589.824c18.1248 0 32.8704-14.7456 32.8704-32.8704 0-18.1248-14.7456-32.8704-32.8704-32.8704zM806.912 479.3344H217.088c-18.1248 0-32.8704 14.7456-32.8704 32.8704 0 18.1248 14.7456 32.8704 32.8704 32.8704h589.824c18.1248 0 32.8704-14.7456 32.8704-32.8704 0-18.1248-14.7456-32.8704-32.8704-32.8704zM806.912 675.7376H217.088c-18.1248 0-32.8704 14.7456-32.8704 32.8704 0 18.1248 14.7456 32.8704 32.8704 32.8704h589.824c18.1248 0 32.8704-14.7456 32.8704-32.8704 0-18.1248-14.7456-32.8704-32.8704-32.8704z"
            p-id="4382"
            fill="#6DA2E8"
          />
        </svg>
        <span>行</span>
      </div>
      <div class="value_class">
        <!-- 是否为空，为空不展示 -->
        <span v-if="isEntriy">增加行</span>
        <!-- 能够拖拽 -->
        <draggable
          class="draggable_value_class"
          v-else
          v-model="rowList"
          group="items"
          @start="drag = true"
          @end="drag = false"
          @change="change"
        >
          <div
            v-for="item in rowList"
            :key="item.code"
            class="feature_value_class"
          >
            <span
              class="featrueValue"
              style="color: #a00"
              >{{ item.title }}</span
            >
            <a-icon
              class="icon_class"
              type="edit"
              @click="editItem(item)"
            />
            <a-icon
              class="icon_class icon_class_delete"
              type="close"
              @click="deletes('col', item.code)"
            />
          </div>
          <a-button
            size="small"
            type="primary"
            shape="round"
            icon="plus-circle"
            @click="add('col')"
          />
        </draggable>
      </div>
    </div>
    <div
      v-if="colConditions && colConditions.length > 0"
      style="display: flex"
    >
      <div class="name_class">
        <svg
          t="1711771605406"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="8088"
          width="20"
          height="20"
        >
          <path
            d="M841.420617 879.065998l-80.003922-0.012839-0.527806-750.839184 80.005349 0.012839zM569.607846 879.07741l-80.003923-0.012839-0.527806-750.839184 80.00535 0.014265zM296.949159 879.074557l-80.407623 0.007133-0.124106-750.837758 80.407623-0.008559z"
            fill="#6DA2E8"
            p-id="8089"
          />
        </svg>
        <span>列</span>
      </div>
      <div class="value_class">
        <span v-if="isEntriy">增加列</span>
        <draggable
          class="draggable_value_class"
          v-else
          v-model="colList"
          group="items"
          @start="drag = true"
          @end="drag = false"
          @change="change"
        >
          <div
            v-for="item in colList"
            :key="item.code"
            class="feature_value_class"
          >
            <span
              class="featrueValue"
              style="color: black"
              >{{ item.title }}</span
            >
            <a-icon
              class="icon_class"
              type="edit"
              @click="editItem(item)"
            />
            <a-icon
              class="icon_class icon_class_delete"
              type="close"
              @click="deletes('row', item.code)"
            />
          </div>
          <a-button
            size="small"
            type="primary"
            shape="round"
            icon="plus-circle"
            @click="add('row')"
          />
        </draggable>
      </div>
    </div>
    <a-drawer
      title="编辑因子"
      placement="right"
      :width="600"
      :closable="false"
      :visible="visible1"
    >
      <a-form
        :form="form1"
        layout="vertical"
      >
        <a-row>
          <a-col>
            <a-form-item label="因子代码：">
              <a-input
                :disabled="true"
                v-decorator="[
                  'code',
                  {
                    rules: [{ required: true, message: '请输入因子代码' }],
                  },
                ]"
                placeholder="请输入因子代码"
              />
            </a-form-item>
          </a-col>
          <a-col>
            <a-form-item label="因子名称：">
              <a-input
                v-decorator="[
                  'label',
                  {
                    rules: [{ required: true, message: '请输入因子名称' }],
                  },
                ]"
                placeholder="请输入因子名称"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-item label="因子描述：">
              <a-textarea
                v-decorator="['desc']"
                placeholder="请输入因子描述"
              />
            </a-form-item>
          </a-col>
          <a-col>
            <a-form-item
              label="是否在表格中可编辑："
              :labelCol="{ span: 8 }"
              :wrapperCol="{ span: 16 }"
            >
              <a-switch v-decorator="['isEditableInRuleTable', { valuePropName: 'checked' }]"></a-switch>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-item label="因子值列表：">
              <div style="text-align: right; margin-bottom: 10px">
                <a-button
                  type="primary"
                  @click="addTableItem"
                  >新增</a-button
                >
              </div>
              <a-table
                v-decorator="['values']"
                :pagination="false"
                :columns="columns"
                :dataSource="data"
                bordered
                rowKey="code"
              >
                <template
                  slot="operation"
                  slot-scope="text, record, index"
                >
                  <a-space>
                    <a @click="editTableItem(record, index)">编辑</a>
                    <a @click="deleteTable(record, index)">删除</a>
                  </a-space>
                </template>
              </a-table>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-drawer
        title="编辑因子值"
        placement="right"
        :closable="false"
        :visible="visible2"
        :width="500"
      >
        <a-form
          :form="form2"
          layout="vertical"
        >
          <a-row>
            <a-col>
              <a-form-item label="值代码：">
                <a-input
                  :disabled="true"
                  v-decorator="[
                    'code',
                    {
                      rules: [{ required: true, message: '请输入值代码' }],
                    },
                  ]"
                  placeholder="请输入值代码"
                />
              </a-form-item>
            </a-col>
            <a-col>
              <a-form-item label="默认匹配规则：">
                <a-select
                  v-decorator="[
                    'matchingRule',
                    {
                      rules: [{ required: true, message: '请选择默认匹配规则' }],
                    },
                  ]"
                  placeholder="请选择默认匹配规则"
                >
                  <a-select-option
                    v-for="item in matchingRuleList"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col>
              <a-form-item label="因子值：">
                <a-select
                  :mode="isMultipleValue(this.form2.getFieldsValue()['matchingRule']) ? 'multiple' : 'default'"
                  v-if="currentItem && currentItem.enumCode"
                  v-decorator="[
                    'data',
                    {
                      rules: [{ required: true, message: '请选择因子值' }],
                    },
                  ]"
                  placeholder="请选择因子值"
                >
                  <a-select-option
                    v-for="item in enums[currentItem.enumCode].values"
                    :key="item.value"
                    :value="item.value"
                    >{{ item.label }}</a-select-option
                  >
                </a-select>
                <a-input
                  v-else
                  v-decorator="[
                    'data',
                    {
                      rules: [{ required: true, message: '请输入因子值' }],
                    },
                  ]"
                  placeholder="请输入因子值"
                />
              </a-form-item>
            </a-col>
            <a-col>
              <a-form-item label="值标签：">
                <a-input
                  v-decorator="[
                    'label',
                    {
                      rules: [{ required: true, message: '请输入值标签' }],
                    },
                  ]"
                  placeholder="请输入值标签"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col>
              <a-form-item label="因子描述：">
                <a-textarea
                  v-decorator="['desc']"
                  placeholder="请输入值描述"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <div
          :style="{
            position: 'absolute',
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e8e8e8',
            padding: '10px 16px',
            textAlign: 'right',
            left: 0,
            background: '#fff',
            borderRadius: '0 0 4px 4px',
          }"
        >
          <a-space>
            <a-button
              style="marginright: 8px"
              @click="onClose2"
              >取消</a-button
            >
            <a-button
              type="primary"
              @click="onSubmit2"
              >确定</a-button
            >
          </a-space>
        </div>
      </a-drawer>
      <div
        :style="{
          position: 'absolute',
          bottom: 0,
          zIndex: 100,
          width: '100%',
          borderTop: '1px solid #e8e8e8',
          padding: '10px 16px',
          textAlign: 'right',
          left: 0,
          background: '#fff',
          borderRadius: '0 0 4px 4px',
        }"
      >
        <a-space>
          <a-button
            style="marginright: 8px"
            @click="onClose"
            >取消</a-button
          >
          <a-button
            type="primary"
            @click="onSubmit"
            >确定</a-button
          >
        </a-space>
      </div>
    </a-drawer>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
import {
  getFactorWithCode,
  updateFactor,
  updateFactorValue,
  getFactorList,
  addFactorValue,
  deleteFactorValue,
  getMatchingTypes,
  isMultipleValue,
  genFactorValuedCode,
} from './api/ruleApi'
import { matchingTypeLabel } from './model/RuleFactorValue'
import enums from './api/enums.json'
export default {
  props: {
    // selectedItems: Object,
    type: String,
    colConditions: Array,
    rowConditions: Array,
  },
  data() {
    return {
      isEntriy: false,
      rowList: [],
      colList: [],
      visible1: false,
      visible2: false,
      form1: this.$form.createForm(this),
      form2: this.$form.createForm(this),
      listAll: [],
      columns: [
        {
          title: '值代码',
          dataIndex: 'code',
          key: 'code',
        },
        {
          title: '默认匹配规则',
          dataIndex: 'matchingRule',
          key: 'matchingRule',
          customRender: (text) => {
            return matchingTypeLabel[text]
          },
        },
        {
          title: '因子值',
          dataIndex: 'data',
          key: 'data',
          customRender: (text) => {
            if (Array.isArray(text)) {
              let showText = ''
              text.forEach((item, index) => {
                showText += item
                if (index !== text.length - 1) showText += '|'
              })
              return showText
            } else {
              return text
            }
          },
        },
        {
          title: '值标签',
          dataIndex: 'label',
          key: 'label',
        },
        {
          title: '值描述',
          dataIndex: 'desc',
          key: 'desc',
        },

        {
          title: '操作',
          width: 100,
          dataIndex: 'operation',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      data: [],
      index: null,
      getFactorWithCode,
      updateFactor,
      updateFactorValue,
      deleteFactorValue,
      addFactorValue,
      getMatchingTypes,
      isMultipleValue,
      genFactorValuedCode,
      currentItem: null,
      enums,
      isAdd: false,
    }
  },
  computed: {
    matchingRuleList() {
      let typeArr = []
      let arr = []
      if (this.currentItem) {
        typeArr = this.getMatchingTypes(this.currentItem.dataType) || []
      }
      typeArr.forEach((item) => {
        arr.push({ value: item, label: matchingTypeLabel[item] })
      })
      return arr
    },
  },
  watch: {
    colConditions: {
      handler(newVal, oldVal) {
        // console.log('colConditions', newVal)
        this.colList = newVal
      },
      deep: true,
      immediate: true,
    },
    rowConditions: {
      handler(newVal, oldVal) {
        this.rowList = newVal
      },
      deep: true,
      immediate: true,
    },
    // selectedItems: {
    //   handler(newVal, oldVal) {
    //     console.log('selctImtes', this.type, newVal)
    //     if (this.type === 'row' || this.showtype === this.RuleTableType.complex) {
    //       this.rowList = newVal.rowConditions
    //     }
    //     if (this.type === 'col' || this.showtype === this.RuleTableType.complex || this.showtype === this.RuleTableType.simple) {
    //       this.colList = newVal.colConditions
    //     }
    //     if (this.type === 'clear') {
    //       this.rowList = []
    //       this.colList = []
    //     }
    //     this.change()
    //   },
    //   deep: true,
    //   immediate: true,
    // },
  },
  components: {
    draggable,
  },
  created() {},
  methods: {
    change() {
      console.log('change-----')
      const arr = {
        colFeature: this.colList,
        rowFeature: this.rowList,
      }
      this.$emit('Listchange', arr)
    },
    add(value) {
      this.$emit('addFeature', value)
    },
    deletes(type, id) {
      if (type === 'row') {
        this.colLsit = this.colLsit.filter((item) => item.code !== id)
      } else {
        this.rowLsit = this.rowLsit.filter((item) => item.code !== id)
      }
      this.change()
    },
    editItem(item) {
      const currentItem = getFactorWithCode(item.code)
      this.currentItem = currentItem
      this.visible1 = true
      this.$nextTick(() => {
        this.form1.setFieldsValue(currentItem)
        this.data = currentItem.options
      })
    },
    addTableItem() {
      this.isAdd = true
      this.visible2 = true
      const record = {
        code: this.genFactorValuedCode(this.currentItem.code),
        data: undefined,
        matchingRule: undefined,
        label: undefined,
        desc: undefined,
      }
      this.$nextTick(() => {
        this.form2.setFieldsValue(record)
      })
    },
    editTableItem(record, index) {
      this.isAdd = false
      this.index = index
      this.visible2 = true
      this.$nextTick(() => {
        this.form2.setFieldsValue(record)
      })
    },
    deleteTable(record) {
      this.$confirm({
        title: '确认删除该条数据？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.deleteFactorValue(this.currentItem.code, record)
          this.data.splice(
            this.data.findIndex((item) => item.code === record.code),
            1
          )
          this.$message.success('删除成功！')
        },
      })
    },
    onSubmit() {
      this.$message.success('保存成功')
      const { dataType, enumCode } = this.currentItem
      this.updateFactor({ ...this.form1.getFieldsValue(), dataType, enumCode, values: this.data })
      this.visible1 = false
      this.index = null
      this.data = []

      this.list2 = this.list2.map((item) => {
        const isFind = getFactorList().find((e) => e.code === item.id)
        return { ...item, values: isFind.values, name: isFind.label }
      })
      this.list = this.list.map((item) => {
        const isFind = getFactorList().find((e) => e.code === item.id)
        return { ...item, values: isFind.values, name: isFind.label }
      })

      // this.list2 = getFactorList()
      //   .filter(item => this.list2.find(e => e.id === item.code))
      //   .map(item => ({ ...item, id: item.code, name: item.label }))
      // this.list = getFactorList()
      //   .filter(item => this.list.find(e => e.id === item.code))
      //   .map(item => ({ ...item, id: item.code, name: item.label }))
      this.change()
    },
    onClose() {
      this.visible1 = false
      this.index = null
      this.data = []
    },
    onClose2() {
      this.visible2 = false
    },
    onSubmit2() {
      if (this.isAdd) {
        this.form2.validateFields((err) => {
          if (!err) {
            this.addFactorValue(this.currentItem.code, this.form2.getFieldsValue())
            this.data.push(this.form2.getFieldsValue())
            this.$message.success('新增成功')
            this.visible2 = false
          }
        })
      } else {
        this.updateFactorValue(this.currentItem.code, this.form2.getFieldsValue())
        this.$set(this.data, this.index, this.form2.getFieldsValue())
        this.$message.success('保存成功')
        this.visible2 = false
      }
    },
  },
}
</script>
<style lang="css" scoped>
.name_class {
  display: flex;
  font-size: 16px;
  align-items: center;
  font-weight: bold;
  padding: 3px 8px;
  width: 100px;
  border: 1px solid rgb(153, 184, 212);
  background-color: rgb(242, 244, 249);
  color: rgb(153, 184, 212);
}
.value_class {
  flex: 1;
  background-color: white;
  font-size: 16px;
  padding: 5px 8px;
  border: 1px solid rgb(153, 184, 212);
  border-left: none;
  opacity: 0.8;
}
.feature_value_class {
  /* 垂直居中 */
  position: relative;
  display: flex;
  margin-right: 10px;
  align-items: center;
  padding: 5px 10px;
  border-radius: 20px;
  color: #7d8ea8;
  background-color: rgb(242, 244, 249);
}
.feature_value_class:hover {
  background-color: #6e89af;
  cursor: pointer;
  color: white;
}
.featrueValue {
  margin-right: 5px;
  font-size: 15px;
  /* 字体间距 */
  letter-spacing: 2px;
}
.icon_class {
  font-size: 12px;
  font-weight: bolder;
  cursor: pointer;
}
.icon_class_delete {
  position: relative;
}
.draggable_value_class {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
</style>
